import React from 'react' // react-dom 依赖于 react, 必须引入
// we'll use this to render our app to an html string
import { renderToString } from 'react-dom/server'
// and these to match the url to routes and then render
import { match, RouterContext } from 'react-router'
import routes from './modules/routes'


var express = require('express'),
    path = require('path'),
		compression = require('compression')

var app = express()

function renderPage(appHtml) {
  return `
	  <!doctype html public="storage">
    <html>
    <meta charset=utf-8/>
    <title>My First React Router App</title>
    <link rel=stylesheet href=/index.css>
    <div id=app>${appHtml}</div>
    <script src="/bundle.js"></script>
		` 
}

app.use(compression())

//point to the right directory for static assets
app.use(express.static(path.join(__dirname, 'public')))

// send all requests to index.html so browserHistory in React Router works
app.get('*', (req, res) => {

  // `RouterContext` is the what `Router` renders. `Router` keeps these
  //     // `props` in its state as it listens to `browserHistory`. But on the
  //         // server our app is stateless, so we need to use `match` to
  //             // get these props before rendering.
  match({routes: routes, location: req.url}, (err, redirect, props) => {
	  console.log(`err: ${err}, redirect: ${redirect}, props: ${props}`);

    if (err) {
      res.status(500).send(err.message)
    } else if (redirect) {
      res.redirect(redirect.pathname + redirect.search)
    } else if (props) {
      // hey we made it!
      const appHtml = renderToString(<RouterContext {...props}/>)

		  // dump the HTML into a template, lots of ways to do this, but none are
      // really influenced by React Router, so we're just using a little
      // function, `renderPage`
      res.send(renderPage(appHtml))
    } else {
      res.status(404).send('Not Found')
    }
	})
})

var PORT = process.env.PORT || 9528
app.listen(PORT, function() {
  console.log('Production Express server running(server rendering) at http://localhost:' + PORT)
})
